<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理 - 表格页面</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
</head>
<body>
    
    <!-- 表格页面 -->
    <div class="layui-fluid" style="padding: 15px;">
        <div class="layui-card">
            <div class="layui-card-header">
                <span>用户管理</span>
                <div class="layui-btn-group" style="float: right;">
                    <button class="layui-btn layui-btn-sm" id="addBtn">
                        <i class="layui-icon layui-icon-add-1"></i> 添加
                    </button>
                </div>
            </div>
            <div class="layui-card-body">
                <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
            </div>
        </div>
    </div>

    <!-- 表格操作栏模板 -->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script src="https://www.layuicdn.com/layui/layui.js"></script>
    <script>
    layui.use(['table', 'layer'], function(){
        var table = layui.table,
            layer = layui.layer,
            $ = layui.$;

        // 模拟数据存储 - 使用window对象确保全局访问
        window.userData = [
            {id: 1, name: '张三', age: 25, email: 'zhangsan@example.com', gender: '男', status: '启用'},
            {id: 2, name: '李四', age: 30, email: 'lisi@example.com', gender: '女', status: '启用'},
            {id: 3, name: '王五', age: 28, email: 'wangwu@example.com', gender: '男', status: '禁用'}
        ];

        // 渲染表格
        window.tableIns = table.render({
            elem: '#userTable',
            data: window.userData,
            cols: [[ 
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'name', title: '姓名', width: 120},
                {field: 'age', title: '年龄', width: 80},
                {field: 'email', title: '邮箱', width: 200},
                {field: 'gender', title: '性别', width: 80},
                {field: 'status', title: '状态', width: 100},
                {title: '操作', toolbar: '#barDemo', width: 150, align: 'center'}
            ]],
            page: false,
            height: 'full-220'
        });

        // 全局函数供子页面调用
        window.refreshTable = function() {
            console.log('刷新表格，当前数据:', window.userData);
            window.tableIns.reload({
                data: window.userData
            });
        };

        window.getUserById = function(id) {
            console.log('查找用户ID:', id);
            for(var i = 0; i < window.userData.length; i++){
                if(window.userData[i].id == id){
                    console.log('找到用户:', window.userData[i]);
                    return window.userData[i];
                }
            }
            console.log('未找到用户');
            return null;
        };

        window.addUser = function(newUserData) {
            console.log('添加用户:', newUserData);
            
            // 生成新ID
            var maxId = 0;
            if(window.userData.length > 0){
                maxId = Math.max.apply(Math, window.userData.map(function(item){
                    return item.id;
                }));
            }
            newUserData.id = maxId + 1;
            
            // 确保数据类型正确
            newUserData.age = parseInt(newUserData.age);
            
            // 添加到数据数组
            window.userData.push(newUserData);
            
            console.log('添加后的数据:', window.userData);
            
            // 刷新表格
            window.refreshTable();
            
            layer.msg('添加成功', {icon: 1});
        };

        window.updateUser = function(updatedUserData) {
            console.log('更新用户:', updatedUserData);
            
            // 确保数据类型正确
            updatedUserData.id = parseInt(updatedUserData.id);
            updatedUserData.age = parseInt(updatedUserData.age);
            
            for(var i = 0; i < window.userData.length; i++){
                if(window.userData[i].id == updatedUserData.id){
                    window.userData[i] = updatedUserData;
                    console.log('用户更新成功:', window.userData[i]);
                    break;
                }
            }
            
            // 刷新表格
            window.refreshTable();
            
            layer.msg('修改成功', {icon: 1});
        };

        // 添加按钮点击事件
        $('#addBtn').on('click', function(){
            console.log('点击添加按钮');
            openUserForm('添加用户', 'add');
        });

        // 表格工具栏事件
        table.on('tool(userTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('确定删除这条记录吗?', function(index){
                    for(var i = 0; i < window.userData.length; i++){
                        if(window.userData[i].id === data.id){
                            window.userData.splice(i, 1);
                            break;
                        }
                    }
                    window.refreshTable();
                    layer.close(index);
                    layer.msg('删除成功', {icon: 1});
                });
            } else if(obj.event === 'edit'){
                console.log('点击编辑按钮, 用户数据:', data);
                openUserForm('修改用户', 'edit', data.id);
            }
        });

        // 打开用户表单
        function openUserForm(title, action, userId) {
            console.log('打开表单:', title, action, userId);
            
            var url = './demo_form.html?action=' + action;
            if(userId) {
                url += '&userId=' + userId;
            }
            
            console.log('表单URL:', url);
            
            layer.open({
                type: 2,
                title: title,
                content: url,
                area: ['500px', '600px'],
                success: function(layero, index){
                    console.log('弹层打开成功');
                },
                end: function() {
                    console.log('弹层关闭');
                }
            });
        }
    });
    </script>
</body>
</html>